package im.yangqiang.android.unicorn.retrofit;

import android.content.Context;

import java.io.File;

import im.yangqiang.android.unicorn.log.ULog;
import im.yangqiang.android.unicorn.retrofit.interceptor.HttpCacheInterceptor;
import im.yangqiang.android.unicorn.retrofit.interceptor.HttpLoggingInterceptor;
import okhttp3.Cache;
import okhttp3.OkHttpClient;

/**
 * OK http网络请求
 * Created by Carlton on 16/9/14.
 */

public class OkHttpUtils
{
    private static OkHttpClient.Builder sBuilder = new OkHttpClient.Builder();
    private static Cache sCache;

    public static OkHttpClient.Builder builder()
    {
        return sBuilder;
    }

    /**
     * 请求
     *  @param context   Context
     * @param cacheTime 缓存时间
     */
    public static OkHttpClient client(Context context, int cacheTime)
    {
        prepare();
        // 缓存 200M
        if (sCache == null)
        {
            sCache = new Cache(new File(context.getCacheDir().getAbsolutePath() + File.separator + "http"), 1024 * 1024 * 200);
        }
        sBuilder.cache(sCache);
        sBuilder.addInterceptor(new HttpCacheInterceptor(context, cacheTime));
        if (ULog.isDebug())
        {
            sBuilder.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));
        }
        return sBuilder.build();
    }

    /**
     * 资源准备
     */
    private static void prepare()
    {
        sBuilder.interceptors().clear();
        sBuilder.networkInterceptors().clear();
    }
}
